﻿package com.orlleite 
{
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFormatAlign;
	import flash.text.TextLineMetrics;
	
	/**
	 * ...
	 * @author Orlando Leite
	 */
	public class ExtendedTextField extends Sprite
	{
		private var letter:Array;
		private var _alpha:Number = 1;
		
		private var content:TextField = new TextField();
		
		public function ExtendedTextField( textfield:TextField ) 
		{
			content = textfield;
			x = textfield.x;
			y = textfield.y;
			updateText();
		}
		
		private function updateText():void
		{
			var i:int;
			
			if ( letter )
			{
				for ( i = 0; letter.length; i++ )
				{
					removeChild( letter[i] );
				}
			}
			
			letter = new Array();
			
			for ( var a:int = 0; a < content.numLines; a++ )
			{
				var lineHeigth:Number = content.getLineMetrics( a ).ascent;
				
				for ( i = content.getLineOffset( a ); i < content.getLineOffset( a ) + content.getLineLength( a ); i++ )
				{
					
					var temp:TextField = new TextField();
					var rect:Rectangle = content.getCharBoundaries( i );
					
					if ( rect != null )
					{
						temp.text = content.text.charAt( i );
						var tempFontFormat:TextFormat = content.getTextFormat( i, i + 1 );
						tempFontFormat.align = TextFormatAlign.LEFT;
						temp.setTextFormat( tempFontFormat );
						temp.selectable = false;
						temp.antiAliasType = content.antiAliasType;
						temp.embedFonts = content.embedFonts;
						temp.cacheAsBitmap = true;
						temp.height = temp.textHeight + 5;
						temp.x = rect.x - 2;
						temp.y = rect.y - 2 + ( lineHeigth - temp.getLineMetrics( 0 ).ascent );
						addChild( temp );
					}
					letter[i] = temp;
				}
			}
		}
		
		public function addEffect( func:Function, type:String, time:Number, delay:Number = 0, params:Object = null ):void
		{
			var dir:Boolean = type == "in" ? true : type == "out" ? false : null;
			
			if ( params )
			{
				params.direction = dir;
				params.length = letter.length;
			}
			else 
			{
				params = { direction:dir, length:letter.length };
			}
			
			for ( var i:int = 0; i < letter.length; i++ )
			{
				func.call( this, letter[i], i, time, delay, params );
			}
		}
		
		override public function get alpha():Number
		{
			return _alpha;
		}
		
		override public function set alpha( value:Number ):void
		{
			_alpha = value;
			for ( var i:int = 0; i < letter.length; i++ )
			{
				letter[i].alpha = _alpha;
			}
		}
		
		public function set text( value:String ):void
		{
			content.text = value;
			updateText();
		}
		
		public function get text():String
		{
			return content.text;
		}
		
		public function set htmlText( value:String ):void
		{
			content.htmlText = value;
			updateText();
		}
		
		public function get htmlText():String
		{
			return content.htmlText;
		}
	}
	
}